package com.loe.httptest

import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseViewHolder
import com.loe.json_ext.*
import com.loe.ktui.ktPx
import com.loe.mvp.BaseActivity
import com.loe.mvp.ext_app.intentSerializableExtra
import com.loe.mvp.ext_java.delay
import com.loe.mvp.ext_view.setDelayClickListener
import com.loe.mvp.list.QuickAdapter
import com.loe.mvp.util.CodeBean
import com.loe.mvp.util.MATCH_PARENT
import com.loe.mvp.util.PopuperList
import kotlinx.android.synthetic.main.activity_http_test_add.*
import kotlinx.android.synthetic.main.item_params.view.*
import java.util.*

class HttpTestAddActivity : BaseActivity()
{
    private var bean by intentSerializableExtra<HttpTestBean>("bean")

    private var isEdit = false

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http_test_add)

        initView()
        initEvent()
    }

    override fun initView()
    {
        isEdit = bean != null
        titleView.titleText = if (isEdit) "修改" else "新增"

        val paramList: ArrayList<HttpParam>
        if (isEdit)
        {
            formName.text = bean!!.name
            formUrl.text = bean!!.url
            paramList = JsonArray(bean!!.params).toList()

            textResult.text = bean!!.result
        } else
        {
            bean = HttpTestBean()
            paramList = ArrayList()
        }
        if (paramList.isEmpty())
        {
            paramList.add(HttpParam())
        }
        paramAdapter.setNewData(paramList)

        recyclerParams.adapter = paramAdapter

        // 变动响应
        formName.setTextListener()
        {
            bean?.name = it
        }
        formUrl.setTextListener()
        {
            bean?.url = it
        }
        formType.setOnSelectListener()
        { i, selectBean ->
            formIsJson.isVisible = selectBean.name != "GET"
            bean?.type = selectBean.name.toLowerCase(Locale.ROOT)
        }
        formIsJson.setOnSelectListener()
        { i, selectBean ->
            bean?.isJson = selectBean.name == "是"
        }
    }

    override fun initEvent()
    {
        // 添加文本参数
        buttonAddParamText.setOnClickListener()
        {
            HttpParseDialog(activity).show()
            {
                var s = it.trim()
                if(!s.startsWith("{")) s = "{$s"
                if(!s.endsWith("}")) s = "$s}"
                val fJson = Json(s)
                for(key in fJson.keys())
                {
                    paramAdapter.addData(HttpParam(key, fJson.get(key)))
                }
            }
        }

        // 添加参数
        buttonAddParam.setOnClickListener()
        {
            paramAdapter.addData(HttpParam())
        }

        // 清空参数
        buttonClearParams.setOnClickListener()
        {
            paramAdapter.data.clear()
            paramAdapter.addData(HttpParam())
        }

        // 清空结果
        buttonClearResult.setOnClickListener()
        {
            textResult.text = ""
            bean?.result = ""
        }

        titleView.setDelayRightListener()
        {
            save()
            toast("保存成功")
            delay(500)
            {
                finish()
            }
        }

        buttonRequest.setDelayClickListener()
        {
            showLoading()
            save()
            bean?.request()
            { s ->
                cancelLoading()
                bean?.putResult(s)
                textResult.text = bean?.result ?: ""
                save()
            }
        }
    }

    private fun save()
    {
        bean?.params = paramAdapter.data.toJsonArrayString()
        if (bean!!.id > 0)
        {
            DbHttpTest.update(bean!!)
        } else
        {
            DbHttpTest.insert(bean!!)
        }
        SpHttpTest.isUpdate = true
    }

    /*************************************** 适配器 **************************************/

    private val typePopuper: PopuperList by lazy()
    {
        val popuperList = PopuperList(activity, ktPx(100))
        popuperList.setStrings("String", "Number", "Boolean")
        popuperList.gravity = Gravity.CENTER
        popuperList.textSize = 12
        popuperList.paddingV = 8
        popuperList.radius = 3
        popuperList
    }

    private val paramAdapter = object : QuickAdapter<HttpParam>(R.layout.item_params)
    {
        override fun View.convert(holder: BaseViewHolder, param: HttpParam)
        {
            editKey.setText(param.key)
            editValue.setText(param.value)
            testValueType.text = param.type

            editKey.setTextListener { param.key = it }
            editValue.setTextListener { param.value = it }
            testValueType.setOnClickListener()
            {
                typePopuper.setOnSelectListener()
                {
                    param.type = it.code
                    testValueType.text = param.type
                }
                typePopuper.show(testValueType, ktPx(-10), 0)
            }

            buttonDelete.setOnClickListener()
            {
                remove(holder.layoutPosition)
            }
        }
    }
}